package com.imglib.glide;

import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.disklrucache.DiskLruCache;
import com.bumptech.glide.load.engine.cache.DiskCache;
import java.io.File;

import com.imglib.glide.cache.MySignature;
import com.imglib.glide.cache.SafeKeyGenerator;

/**
 */
public class ImageLoader {

    /**
     * 获取是否有某张原图的缓存
     * 缓存模式必须是：DiskCacheStrategy.SOURCE  才能获取到缓存文件
     */
    public static File getGlideCacheFile(Context context, String url) {
        try {
            MySignature mySignature = new MySignature(url);
            String safeKey2 = new SafeKeyGenerator().getSafeKey( mySignature);
            // 注意此处缓存的路径要跟 glide 设置的缓存路径一致
            File file = new File(MyGlide.diskCachePath);
            DiskLruCache diskLruCache = DiskLruCache.open(file, 1, 1, DiskCache.Factory.DEFAULT_DISK_CACHE_SIZE);
            DiskLruCache.Value value = diskLruCache.get(safeKey2);
            if (value != null) {
                return value.getFile(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void clearMemory(AppCompatActivity activity) {
        Glide.get(activity.getApplicationContext()).clearMemory();
    }


    /**
     * 清除磁盘缓存
     */
    public static void cleanDiskCache(final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(context.getApplicationContext()).clearDiskCache();
            }
        }).start();
    }
}